<template>
	<view class="page-history-record">
		<!-- 页面标题栏 -->
		<view class="page-header">
			<view class="header-content">
				<view class="back-btn" @tap="goBack">
					<u-icon name="arrow-left" size="24" color="#333"></u-icon>
				</view>
				<text class="page-title">历史记录</text>
				<view class="placeholder"></view>
			</view>
		</view>

		<!-- 加载状态 -->
		<view class="loading-container" v-if="loading && historyRecords.length === 0">
			<text class="loading-text">加载中...</text>
		</view>

		<!-- 历史记录列表 -->
		<view class="history-list" v-else>
			<!-- 空状态 -->
			<view class="empty-state" v-if="historyRecords.length === 0 && !loading">
				<text class="empty-text">暂无历史记录</text>
			</view>
			
			<view class="history-card" v-for="(record, index) in historyRecords" :key="record.id">
				<!-- 卡片头部 -->
				<view class="card-header">
					<text class="activity-title">{{ record.title }}</text>
					<view class="status-tag" :class="record.statusClass">
						<text class="status-text">{{ record.status }}</text>
					</view>
				</view>

				<!-- 活动信息 -->
				<view class="activity-info">
					<text class="info-text">老人姓名：{{ record.elderName }}</text>
					<text class="info-text">活动时间：{{ record.activityTime }}</text>
					<text class="info-text">完成时间：{{ record.completedTime }}</text>
				</view>

				<!-- 活动描述 -->
				<view class="activity-description">
					<text class="description-text">活动描述：{{ record.description }}</text>
				</view>

				<!-- 活动图片 -->
				<view class="activity-images" v-if="record.imgurl">
					<image class="activity-image" :src="record.imgurl" mode="aspectFill" @tap="previewImage(record.imgurl)" />
				</view>
			</view>
			
			<!-- 加载更多提示 -->
			<view class="load-more-container" v-if="historyRecords.length > 0">
				<view class="load-more-tip" v-if="loadMoreStatus === 'loading'">
					<text class="load-more-text">加载中...</text>
				</view>
				<view class="load-more-tip" v-else-if="loadMoreStatus === 'noMore'">
					<text class="load-more-text">没有更多数据了</text>
				</view>
				<view class="load-more-tip" v-else-if="loadMoreStatus === 'more'">
					<text class="load-more-text">上拉加载更多</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import { apiGetHistoryRecords } from '@/request/api.js'

export default {
	data() {
		return {
			historyRecords: [],
			// 分页参数
			pageInfo: {
				page: 1,
				limit: 10,
				total: 0
			},
			// 加载状态
			loading: false,
			loadMoreStatus: 'more', // more/loading/noMore
			// 用户信息
			memberId: 1 // 默认老人ID，实际应从用户选择或路径参数获取
		}
	},
	onLoad(options) {
		// 页面加载时的初始化
		if (options.member_id) {
			this.memberId = options.member_id;
		}
		// 加载历史记录
		this.loadHistoryRecords();
	},
	
	// 页面下拉刷新
	onPullDownRefresh() {
		this.refreshData();
	},
	
	// 页面上拉触底
	onReachBottom() {
		this.loadMore();
	},
	methods: {
		// 加载历史记录
		async loadHistoryRecords(isRefresh = false) {
			if (this.loading) return;
			
			this.loading = true;
			
			try {
				// 如果是刷新，重置页码
				if (isRefresh) {
					this.pageInfo.page = 1;
					this.historyRecords = [];
				}
				
				// 构建请求参数
				const data = {
					member_id: this.memberId,
					page: this.pageInfo.page,
					limit: this.pageInfo.limit
				};
				
				const response = await apiGetHistoryRecords(data);
				
				if (response.code === 0) {
					const { data: records, count } = response;
					
					// 处理数据
					const processedRecords = this.processHistoryRecords(records || []);
					
					if (isRefresh) {
						this.historyRecords = processedRecords;
					} else {
						this.historyRecords = [...this.historyRecords, ...processedRecords];
					}
					
					this.pageInfo.total = count || 0;
					
					// 更新加载更多状态
					if (this.historyRecords.length >= this.pageInfo.total) {
						this.loadMoreStatus = 'noMore';
					} else {
						this.loadMoreStatus = 'more';
					}
				} else {
					uni.showToast({
						title: response.msg || '获取历史记录失败',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('加载历史记录失败:', error);
				uni.showToast({
					title: '加载失败，请重试',
					icon: 'none'
				});
			} finally {
				this.loading = false;
				// 停止下拉刷新
				uni.stopPullDownRefresh();
			}
		},
		
		// 处理历史记录数据
		processHistoryRecords(records) {
			return records.map(record => {
				// 根据type确定活动类型
				const typeMap = {
					1: '娱乐活动',
					2: '用药提醒',
					3: '健康检查',
					4: '饮食管理',
					8: '巡检任务'
				};
				
				// 处理时间显示
				const eventTime = record.event_time || record.create_time;
				const updateTime = record.update_time;
				
				// 历史记录都是已完成状态
				const status = { text: '已完成', class: 'completed' };
				
				return {
					id: record.id,
					title: record.title || typeMap[record.type] || '活动记录',
					status: status.text,
					statusClass: status.class,
					elderName: record.name || '未知',
					activityTime: this.formatDateTime(eventTime),
					completedTime: this.formatDateTime(updateTime),
					description: record.desc || record.num_desc || '暂无描述',
					imgurl: record.imgurl && record.imgurl !== 'https://nursing.mguit.com1' ? record.imgurl : '',
					rawData: record // 保存原始数据
				};
			});
		},
		
		// 格式化完整日期时间
		formatDateTime(timeStr) {
			if (!timeStr || timeStr === '1970.01.01' || timeStr === null) return '暂无时间';
			
			try {
				const date = new Date(timeStr);
				const year = date.getFullYear();
				const month = (date.getMonth() + 1).toString().padStart(2, '0');
				const day = date.getDate().toString().padStart(2, '0');
				const hours = date.getHours().toString().padStart(2, '0');
				const minutes = date.getMinutes().toString().padStart(2, '0');
				const seconds = date.getSeconds().toString().padStart(2, '0');
				return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			} catch (e) {
				return '时间格式错误';
			}
		},
		
		// 刷新数据
		refreshData() {
			this.loadHistoryRecords(true);
		},
		
		// 加载更多
		loadMore() {
			if (this.loadMoreStatus !== 'more' || this.loading) return;
			
			this.loadMoreStatus = 'loading';
			this.pageInfo.page += 1;
			this.loadHistoryRecords();
		},
		
		// 返回上一页
		goBack() {
			uni.navigateBack();
		},
		
		// 预览图片
		previewImage(imageUrl) {
			uni.previewImage({
				urls: [imageUrl],
				current: imageUrl
			});
		}
	}
}
</script>

<style lang="scss" scoped>
.page-history-record {
	min-height: 100vh;
	background: #F8F8F8;
}

.page-header {
	background: #FFFFFF;
	padding: 20rpx 30rpx 20rpx;
	margin-top: 60rpx;
	border-bottom: 1rpx solid #E5E5E5;
	position: relative;
}

.header-content {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding-top: 20rpx;
	position: relative;
}

.back-btn {
	width: 60rpx;
	height: 60rpx;
	display: flex;
	justify-content: center;
	align-items: center;
}

.page-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333333;
	position: absolute;
	left: 50%;
	transform: translateX(-50%);
}

.placeholder {
	width: 60rpx;
}

.history-list {
	padding: 20rpx 16rpx;
}

.history-card {
	background: #FFFFFF;
	border-radius: 16rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
	border: 1rpx solid #F0F0F0;
}

.card-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 24rpx;
}

.activity-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333333;
	flex: 1;
}

.status-tag {
	display: flex;
	align-items: center;
	padding: 8rpx 16rpx;
	border-radius: 20rpx;
}

.status-tag.completed {
	background: #E8F5E8;
	border: 1rpx solid #4CAF50;
}

.status-text {
	font-size: 22rpx;
	font-weight: 500;
	color: #4CAF50;
}

.activity-info {
	margin-bottom: 20rpx;
}

.info-text {
	display: block;
	font-size: 26rpx;
	color: #666666;
	margin-bottom: 8rpx;
}

.activity-description {
	background: #F8F9FA;
	padding: 20rpx;
	border-radius: 12rpx;
	margin-bottom: 20rpx;
	border-left: 4rpx solid #4CAF50;
}

.description-text {
	font-size: 26rpx;
	color: #333333;
	line-height: 1.6;
}

.activity-images {
	margin-top: 20rpx;
}

.activity-image {
	width: 200rpx;
	height: 200rpx;
	border-radius: 12rpx;
	border: 1rpx solid #E0E0E0;
}

/* 加载状态样式 */
.loading-container {
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 80rpx 0;
}

.loading-text {
	font-size: 28rpx;
	color: #999999;
}

/* 空状态样式 */
.empty-state {
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 120rpx 0;
}

.empty-text {
	font-size: 28rpx;
	color: #999999;
}

/* 加载更多样式 */
.load-more-container {
	padding: 30rpx 0;
}

.load-more-tip {
	display: flex;
	justify-content: center;
	align-items: center;
}

.load-more-text {
	font-size: 24rpx;
	color: #999999;
}
</style>
